import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import mongoose from 'mongoose';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { IoAdapter } from '@nestjs/platform-socket.io';
import { TransformInterceptor } from './interceptors/transform.interceptor';
import { GlobalExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
  try {
    // 配置 Mongoose 全局错误处理
    mongoose.connection.on('error', (err) => {
      console.error('MongoDB connection error:', err);
    });

    mongoose.connection.on('disconnected', () => {
      console.log('MongoDB disconnected. Attempting to reconnect...');
    });

    mongoose.connection.on('connected', () => {
      console.log('MongoDB connected successfully');
    });

    const app = await NestFactory.create<NestExpressApplication>(AppModule);

    // 配置静态文件服务
    app.useStaticAssets(join(__dirname, '..', 'uploads'), {
      prefix: '/uploads/',
    });

    // 配置全局前缀
    app.setGlobalPrefix('api');

    // 配置跨域
    app.enableCors({
      origin: '*',  // 仅在开发环境使用，生产环境应限制来源
      methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
      allowedHeaders: 'Content-Type,Accept,Authorization',
      credentials: false
    });

    // 配置全局验证管道
    app.useGlobalPipes(new ValidationPipe());

    // 配置Swagger文档
    const config = new DocumentBuilder()
      .setTitle('AI绘画工作流API')
      .setDescription('AI绘画工作流系统后端API文档')
      .setVersion('1.0')
      .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api-docs', app, document);

    // 使用 Socket.io 适配器
    app.useWebSocketAdapter(new IoAdapter(app));

    // 添加全局响应转换拦截器
    app.useGlobalInterceptors(new TransformInterceptor());

    // 添加全局异常过滤器
    app.useGlobalFilters(new GlobalExceptionFilter());

    const port = process.env.PORT || 3000;
    const host = process.env.HOST || '127.0.0.1';
    await app.listen(port, host);
    console.log(`Server running on http://${host}:${port}`);
  } catch (error) {
    console.error('Application failed to start:', error);
    process.exit(1);
  }
}

bootstrap();